﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;
using System.Reflection;
using System.Data;
using SDK;
using Common;

namespace eBay {
    public partial class API {

        public class OfficialTime {
            public static DateTime GetOfficialTime() {
                #region Load The XML Document Template and Set the Neccessary Values
                //Load the XML Document to Use for this Request
                XmlDocument xmlDoc = new XmlDocument();

                //Get XML Document from Embedded  Resources
                xmlDoc.Load(Common.Funcs.GetAppPath() + "APICalls\\GeteBayOfficialTimeRequest.xml");

                //Set the various node values
                xmlDoc["GeteBayOfficialTimeRequest"]["RequesterCredentials"]["eBayAuthToken"].InnerText = Global.Configuration.UserToken;


                //Get XML into a string for use in encoding
                string xmlText = xmlDoc.InnerXml;


                //Put the data into a UTF8 encoded  byte array
                UTF8Encoding encoding = new UTF8Encoding();
                int dataLen = encoding.GetByteCount(xmlText);
                byte[] utf8Bytes = new byte[dataLen];
                Encoding.UTF8.GetBytes(xmlText, 0, xmlText.Length, utf8Bytes, 0);
                #endregion

                #region Send The Request
                HttpWebRequest request = eBayRequest.SetupRequest("GeteBayOfficialTime", utf8Bytes.Length, 551);
                Stream str = null;
                try {
                    //Set the request Stream
                    str = request.GetRequestStream();
                    //Write the equest to the Request Steam
                    str.Write(utf8Bytes, 0, utf8Bytes.Length);
                    str.Close();
                    //Get response into stream
                    WebResponse resp = request.GetResponse();
                    str = resp.GetResponseStream();
                }
                catch (WebException wEx) {
                    //Error has occured whilst requesting
                    //Display error message and exit.
                    if (wEx.Status == WebExceptionStatus.Timeout)
                        throw new API.Exceptions.TimeOutCustomException();
                    else
                        throw new API.Exceptions.UnknownException(wEx.Message);
                }
                #endregion

                #region Process Response
                // Get Response into String
                StreamReader sr = new StreamReader(str);
                xmlDoc.LoadXml(sr.ReadToEnd());
                sr.Close();
                str.Close();

                //get the root node, for ease of use
                XmlNode root = xmlDoc["GeteBayOfficialTimeResponse"];

                //There have been Errors
                if (root["Errors"] != null) {
                    string errorCode = root["Errors"]["ErrorCode"].InnerText;
                    string errorShort = root["Errors"]["ShortMessage"].InnerText;
                    string errorLong = root["Errors"]["LongMessage"].InnerText;

                    //Output the error message
                    throw new API.Exceptions.UnknownException(errorCode + " ERROR: " + errorShort + "\n\t" + errorLong + "\n");
                    //Console.WriteLine(errorCode + " ERROR: " + errorShort);
                    //Console.WriteLine(errorLong + "\n");
                }
                else {
                    //Get Result String
                    string theTime = root["Timestamp"].InnerText;
                    //Put into a DateTime object
                    DateTime dt = DateTime.Parse(theTime);
                    //Display the result
                    return dt;
                }
                #endregion

            }
        }

        public static class Exceptions {
            public class NoQueryKeywordsSetException : Exception { }
            public class NoQueryParametersSetException : Exception { }
            public class TimeOutCustomException : Exception { }
            public class UnknownException : Exception { public UnknownException(string Message) : base(Message) { } }
        }
    }
}
